<template>
<div>
  <!-- 面包屑-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--卡片视图区-->
  <el-card>
    <!--收搜与添加区-->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
          <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
    <!--用户列表区-->
    <el-table :data="userList" border stripe>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="姓名" prop="username"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="电话" prop="mobile"></el-table-column>
      <el-table-column label="角色" prop="role_name"></el-table-column>
      <el-table-column label="状态">
        <!--作用域插槽-->
        <template slot-scope="scope">
          <el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <!--作用域插槽-->
        <template slot-scope="scope">
          <!--修改按钮-->
          <el-button type="primary" size="mini" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
          <!--删除按钮-->
          <el-button type="danger" size="mini" @click="removeUserById(scope.row.id)" icon="el-icon-delete"></el-button>
          <!--文字提示-->
          <el-tooltip effect="dark" content="分配角色" placement="top" :hide-after="1000" :enterable="false">
            <!--分配角色按钮-->
            <el-button type="warning" size="mini" @click="setRole(scope.row)" icon="el-icon-setting"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--分页区域-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
  </el-card>

  <!--添加用户对话框-->
  <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
    <!--内容主体区域-->
    <el-form :model="addFrom" :rules="addFromRules" ref="addFormRef" label-width="70">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addFrom.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="addFrom.password"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addFrom.email"></el-input>
      </el-form-item>

      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="addFrom.mobile"></el-input>
      </el-form-item>
    </el-form>
    <!--底部区域-->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="adduser">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 修改用户信息对话框-->
  <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
    <!--修改用户信息表单-->
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editUserInfo">确 定</el-button>
    </span>
  </el-dialog>

  <!--分配角色对话框-->
  <el-dialog title="分配角色" :visible.sync='setRoleDialogVisible' width="50%" @close='setRoleDialogClosed'>
    <div>
      <p>当前的用户: {{userInfo.username}}</p>
      <p>当前的角色: {{userInfo.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRoleDialogVisible= false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    // 自定义表单效验规则
    // 验证邮箱规则
    var checkEmail = (rule, value, cd) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cd();
      }

      cd(new Error("请输入合法的邮箱"));
    };
    // 验证手机号规则
    var checkMobile = (rule, value, cd) => {
      // 验证手机号码的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cd();
      }
      cd(new Error("请输入合法的手机号"));
    };
    //----------------------------------------------------------------
    return {
      // 请求参数
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      // 请求数据储存的数组
      userList: [],
      // 所有角色数据列表
      rolesList: [],
      // 数据总数
      total: 0,
      // 用于控制 添加用户 对话框的 显示与隐藏
      addDialogVisible: false,
      // 用于控制 修改用户 对话框的 显示与隐藏
      editDialogVisible: false,
      // 用于控制 角色分配 对话框 的显示与隐藏
      setRoleDialogVisible: false,

      // 添加用户表单数据
      addFrom: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 查询到的用户信息对象
      editForm: {},
      // 需要被分配 角色的用户信息
      userInfo: {},
      // select 已选中的角色的id值
      selectedRoleId: '',
      // 添加 用户信息 表单规则
      addFromRules: {
        username: [{
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在3-10个之间",
            trigger: "blur",
          },
        ],
        password: [{
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 6,
            message: "长度最少6个单位",
            trigger: "blur",
          },
        ],
        email: [{
            required: true,
            message: "邮箱不能为空",
            trigger: "blur",
          },

          {
            //自定义表单规则
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [{
            required: true,
            message: "电话不能为空",
            trigger: "blur",
          },

          {
            //  自定义 表单规则
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      // 修改 用户信息 表单规则
      editFormRules: {
        email: [{
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [{
            required: true,
            message: "请输入电话",
            trigger: "blur",
          },
          {
            //  自定义 表单规则
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const {
        data: res
      } = await this.$http.get("users", {
        params: this.queryInfo,
      });

      if (res.meta.status == !200)
        return this.$message.error("获取用户列表失败");
      this.userList = res.data.users;
      this.total = res.data.total;
      // console.log(res)
    },

    // 监听 pagination 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },

    // 监听页码值 改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 监听 switch 开关状态的改变 并提交
    async userStateChanged(userinfo) {
      // console.log(userinfo);
      const {
        data: res
      } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("修改失败");
      }
      this.$message.success(res.meta.msg);
    },
    // 监听 添加用户 对话框消失
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听 修改用户 对话框消失
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 监听 分配角色 对话框消失
    setRoleDialogClosed() {
      this.userinfo = {}
      this.selectedRoleId = ''
    },

    // 点击添加用户预校验 并提交
    adduser() {
      this.$refs.addFormRef.validate(async (value) => {
        if (!value) return;
        const {
          data: res
        } = await this.$http.post("users", this.addFrom);

        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        // 成功后关闭对话框
        this.addDialogVisible = false;
        // 重新更新用户列表
        this.getUserList();
      });
    },

    // 点击 修改用户信息 预效验 并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (value) => {
        if (!value) return;
        const {
          data: res
        } = await this.$http.put(
          `users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.editDialogVisible = false;
        this.getUserList();
      });
    },

    // 展示用户信息修改的对话框
    async showEditDialog(id) {
      this.editDialogVisible = true;
      const {
        data: res
      } = await this.$http.get(`users/${id}`);

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // this.$message.success(res.meta.msg);
      this.editForm = res.data;
      // console.log(this.editForm);
      this.editDialogVisible = true;
    },
    // 根据用户ID删除对应的 用户数据
    async removeUserById(id) {
      try {
        const confirmResult = await this.$confirm(
          "此操作将永久删除该用户, 是否继续?",
          "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        // 用户点击确认, 则返回字符串 confirm
        // console.log(confirmResult)

        const {
          data: res
        } = await this.$http.delete(`users/${id}`);

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg)

        this.getUserList();

      } catch (err) {
        // 用户点击取消, 则返回字符串 cancel
        // console.log(err)
        this.$message.info("已经取消删除");
      }
    },

    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前, 获取所有角色的列表
      const {
        data: res
      } = await this.$http.get('roles')

      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data

      console.log(this.rolesList)
      this.setRoleDialogVisible = true
    },
    // 点击 确认按钮 分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) return this.$message.error('请选择要分配的角色');
      const {
        data: res
      } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })

      if (res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.setRoleDialogVisible = false;
      this.getUserList();
      this.$message.success(res.meta.msg)

    }
  },
};
</script>

<style lang="less" scoped>
</style>
